package com.example.userdemo.controller;

import com.example.userdemo.annotation.LogOperation;
import com.example.userdemo.entity.User;
import com.example.userdemo.repository.UserRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 创建用户
    @PostMapping
    @LogOperation("创建用户")
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    // 获取所有用户
    @GetMapping
    @LogOperation("查询所有用户")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 获取单个用户
    @GetMapping("/{id}")
    @LogOperation("查询单个用户")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        return userRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 更新用户
    @PutMapping("/{id}")
    @LogOperation("更新用户")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        return userRepository.findById(id)
                .map(existingUser -> {
                    existingUser.setName(user.getName());
                    existingUser.setEmail(user.getEmail());
                    return ResponseEntity.ok(userRepository.save(existingUser));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    // 删除用户
    @DeleteMapping("/{id}")
    @LogOperation("删除用户")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}